package com.qiteng.apiclientsdk.client;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

import static com.qiteng.apiclientsdk.utils.SignUtils.generateSign;


/**
 * @author qiteng
 */
public class ApiClient {

    Gson gson = new Gson();
    private String accessKey;
    private String secretKey;
    private static final String GATEWAY_ADDRESS = "http://localhost:8090";

    public ApiClient() {
    }

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    /**
     * 调用接口
     *
     * @param params
     * @param path
     * @param method
     * @return
     */
    public String invokeInterface(String params, String path, String method) {
        //如果请求方法为空
        if (StringUtils.isBlank(method)) {
            return null;
        }

        //判断是get还是post请求
        if ("GET".equals(method)) {
            return doGet(params, path);
        } else {
            return doPost(params, path);
        }
    }

    /**
     * 发送GET请求
     *
     * @param params
     * @param path
     * @return
     */
    private String doGet(String params, String path) {
        //如果路径为空
        if (StringUtils.isBlank(path)) {
            return null;
        }

        //获得url
        String url = GATEWAY_ADDRESS + path;
        //无论有没有参数都要做下列处理，统一request发送到接口服务器
        params = params.replace("\"", "\\" + "\"");
        //拼接后例子：{"paramsJson": "{\"name\":\"qiteng\"}"}
        params = "{" + "\"paramsJson\": " + "\"" + params + "\"" + "}";
        //发送get请求
        String result = HttpRequest.get(url)
                .body(params)
                .addHeaders(getHeaderMap(params))
                .execute().body();
        return result;
    }

    /**
     * 发送POST请求
     *
     * @param params
     * @param path
     */
    private String doPost(String params, String path) {
        //如果路径为空
        if (StringUtils.isBlank(path)) {
            return null;
        }
        //无论有没有参数都要做这个处理，统一request发送到接口服务器
        params = params.replace("\"", "\\" + "\"");
        //拼接后例子：{"paramsJson": "{\"name\":\"qiteng\"}"}
        params = "{" + "\"paramsJson\": " + "\"" + params + "\"" + "}";
        //发送post请求
        String result = HttpRequest.post(GATEWAY_ADDRESS + path)
                .body(params)
                .addHeaders(getHeaderMap(params))
                .execute().body();
        return result;
    }

    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> headers = new HashMap<>();
        headers.put("accessKey", accessKey);
        headers.put("body", body);
        headers.put("nonce", RandomUtil.randomNumbers(4));
        headers.put("timestamp", String.valueOf(System.currentTimeMillis()));
        headers.put("sign", generateSign(body, secretKey));
        return headers;
    }
}
